//
//  WPDiseaseTypesCVC.m
//  wobingwoyi
//
//  Created by WGP on 16/9/5.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPDiseaseTypesCVC.h"
#import "WPReadingFamousDoctorCell.h"
#import "WPMineLoginVC.h"

@interface WPDiseaseTypesCVC ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,assign)int page;

@end
@implementation WPDiseaseTypesCVC

-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        self.page = 1;
        self.tableView = [[UITableView alloc] init];
        self.tableView.backgroundColor = GlobalBgColor;
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.tableView.rowHeight = 165;
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        [self.tableView registerClass:[WPReadingFamousDoctorCell class] forCellReuseIdentifier:@"WPReadingFamousDoctorCell"];
        [self.contentView addSubview:self.tableView];
        
        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.contentView);
        }];
        
         __weak typeof(self) weakSelf = self;
        /* 配置下拉刷新控件 */
        MJRefreshNormalHeader *mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            //      刷新数据
            [weakSelf refreshData];
            
        }];
        self.tableView.mj_header = mj_header;
        [mj_header setTitle:@"下拉可以刷新" forState:MJRefreshStateIdle];
        [mj_header setTitle:@"松开立即刷新" forState:MJRefreshStatePulling];
        [mj_header setTitle:@"正在刷新" forState:MJRefreshStateRefreshing];
        mj_header.stateLabel.textColor = GLobalFontColor;
        mj_header.lastUpdatedTimeLabel.textColor = GLobalFontColor;
        
        //    上拉刷新控件
        MJRefreshAutoFooter *mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            
            [weakSelf loadMoreData];
            [mj_footer endRefreshing];
        }];
        self.tableView.mj_footer = mj_footer;
        mj_footer.automaticallyRefresh = NO;
        mj_footer.automaticallyHidden = NO;
    }
    return self;
}

-(void)loadData
{
    [self showWithStatus:@"正在加载"];
    
    [[WPNetWorkManager sharedNetWorkManager] POST:self.url parameters:self.parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *responseDict = (NSDictionary *)responseObject;
        
        if ([responseDict[@"result"] isEqualToString:@"success"])
        {
            
            for (NSDictionary *dict in responseDict[@"detail"])
            {
                WPMRModel *model = [WPMRModel yy_modelWithDictionary:dict];
                [self.models addObject:model];
            }
            
            if([responseDict[@"detail"] count] < 10)
            {
                self.tableView.mj_footer.hidden = YES;
            }
            else
            {
                self.tableView.mj_footer.hidden = NO;
            }
            
            [self.tableView reloadData];
            [self dismiss];
        }
        else
        {
            //            考虑到账号过期的情况
            if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
            {
                //                账号过期
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"账号过期,请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alertView show];
            }
            else
            {
                [self showErrorInfoWithStatus:@"网络错误"];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self showErrorInfoWithStatus:@"网络错误"];
        
    }];
}

//重新登陆的代理方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
//    if (buttonIndex == 0)
//    {
//        WPMineLoginVC *vc = [WPMineLoginVC new];
//        [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
//    }
//    弹出登录框
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.models.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WPReadingFamousDoctorCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WPReadingFamousDoctorCell"];
    cell.model = self.models[indexPath.item];
    return cell;
}

-(void)refreshData
{
    self.parameters[@"page"] = @(0);
    
    self.page = 1;
    
    [self.tableView.mj_footer endRefreshing];
    
    [[WPViewModel sharedInstance] loadDataWithURL:self.url parameters:self.parameters finished:^(NSArray *dictsArr, NSError *error) {
        
        if (dictsArr.count)
        {
            if (self.models == nil)
            {
                self.models = [NSMutableArray array];
            }
            
            [self.models removeAllObjects];
            
            for (NSDictionary *dict in dictsArr)
            {
                WPMRModel *model = [WPMRModel yy_modelWithDictionary:dict];
                [self.models addObject:model];
            }
            
            [self.tableView reloadData];
        }
        
        [self.tableView.mj_header endRefreshing];
    }];
}

-(void)loadMoreData
{
    self.parameters[@"page"] = @(self.page);
    
    [[WPViewModel sharedInstance] loadDataWithURL:self.url parameters:self.parameters finished:^(NSArray *dictsArr, NSError *error) {
        
        if (dictsArr.count)
        {
            for (NSDictionary  *obj in dictsArr)
            {
                WPMRModel *model = [WPMRModel yy_modelWithDictionary:obj];
                [self.models addObject:model];
            }
            
            self.page++;
            //            刷新数据
            [self.tableView reloadData];
            
            if (dictsArr.count < 10)
            {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            else
            {
                [self.tableView.mj_footer endRefreshing];
            }
        }
        else
        {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
    }];
}

-(void)setUrl:(NSString *)url
{
    _url = url;
    if (_parameters != nil)
    {
        [self loadData];
    }
}

-(void)setParameters:(id)parameters
{
    _parameters = parameters;
    if (_url != nil)
    {
        [self loadData];
    }
}


-(NSMutableArray *)models
{
    if (_models == nil)
    {
        _models = [NSMutableArray array];
    }
    return _models;
}

@end
